package com.mashibing.apipassenger.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.mashibing.apipassenger.service.ServiceSmsRestTemplateService;
import com.mashibing.apipassenger.service.ServiceVerificationCodeRestTemplateService;
import com.mashibing.apipassenger.service.VerificationCodeService;
import com.mashibing.internalcommon.constant.CommonStatusEnum;
import com.mashibing.internalcommon.constant.IdentityConstant;
import com.mashibing.internalcommon.dto.ResponseResult;
import com.mashibing.internalcommon.dto.serviceverificationcode.response.VerifyCodeResponse;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author gorkr
 * @date 2022/05/29 09:43
 **/
@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {

    @Resource
    private ServiceVerificationCodeRestTemplateService serviceVerificationCodeRestTemplateService;

    @Resource
    private ServiceSmsRestTemplateService serviceSmsRestTemplateService;

    @Override
    public ResponseResult send(String phoneNumber) {
        ResponseResult responseResult = serviceVerificationCodeRestTemplateService.generatorCode(IdentityConstant.PASSENGER, phoneNumber);
        VerifyCodeResponse verifyCodeResponse = null;
        if(responseResult.getCode() == CommonStatusEnum.SUCCESS.getCode()){

            verifyCodeResponse = (VerifyCodeResponse) JSONObject.parse(responseResult.getData().toString());
        }else {
            return ResponseResult.fail("获取验证码失败");
        }

        // 获取到验证码
        String code = verifyCodeResponse.getCode();

        ResponseResult smsResult = serviceSmsRestTemplateService.sendSms(phoneNumber, code);
        if(smsResult.getCode()!=CommonStatusEnum.SUCCESS.getCode()){
            return ResponseResult.fail("发送短信 失败");
        }

        return ResponseResult.success("");
    }

    @Override
    public ResponseResult verify(String phoneNumber, String code) {

        return serviceVerificationCodeRestTemplateService.verifyCode(IdentityConstant.PASSENGER,phoneNumber,code);
    }
}
    